<template>
  <div class="creation-square">
    <!-- 顶部横幅区域 -->
    <div class="banner-section">
      <div class="banner-content">
        <h1 class="banner-title">创作广场</h1>
        <p class="banner-subtitle">发现社区中精彩的创作作品，与创作者互动交流</p>
        <div class="banner-stats">
          <div class="stat-item">
            <span class="stat-number">{{ totalWorks }}</span>
            <span class="stat-label">作品总数</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ activeUsers }}</span>
            <span class="stat-label">活跃创作者</span>
          </div>
        </div>
      </div>
    </div>

    <div class="container">
      <!-- 筛选区域 -->
      <div class="filter-section">
        <div class="section-header">
          <h3>筛选作品</h3>
          <p>根据您的偏好筛选出最感兴趣的作品</p>
        </div>

        <div class="filter-bar">
          <!-- 分类筛选 -->
          <div class="filter-group">
            <label class="filter-label">作品分类</label>
            <el-select
                v-model="queryParams.cgyId"
                placeholder="全部分类"
                size="small"
                @change="handleSearch"
                class="filter-select"
            >
              <el-option value="" label="全部分类"></el-option>
              <el-option
                  v-for="category in categories"
                  :key="category.cgy_id"
                  :value="category.cgy_id"
                  :label="category.cgy_name"
              ></el-option>
            </el-select>
          </div>

          <!-- 排序方式 -->
          <div class="filter-group">
            <label class="filter-label">排序方式</label>
            <el-select
                v-model="sortOption"
                placeholder="排序方式"
                size="small"
                @change="handleSortChange"
                class="filter-select"
            >
              <el-option value="createTime_desc" label="最新发布"></el-option>
              <el-option value="click_desc" label="最多点击"></el-option>
              <el-option value="liked_desc" label="最多点赞"></el-option>
              <el-option value="createTime_asc" label="最早发布"></el-option>
            </el-select>
          </div>

          <!-- 搜索框 -->
          <div class="filter-group">
            <label class="filter-label">搜索作品</label>
            <el-input
                v-model="queryParams.keyword"
                placeholder="搜索作品或作者"
                size="small"
                class="search-input"
                prefix-icon="Search"
                @keyup.enter="handleSearch"
            ></el-input>
          </div>
        </div>

        <!-- 高级筛选区域 -->
        <div class="advanced-filter">
          <el-collapse v-model="activeAdvancedFilters">
            <el-collapse-item title="高级筛选" name="advanced">
              <div class="filter-group advanced-group">
                <!-- 时间范围筛选 -->
                <div class="filter-item">
                  <label class="filter-label">发布时间</label>
                  <el-date-picker
                      v-model="dateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      size="small"
                      @change="handleDateRangeChange"
                  ></el-date-picker>
                </div>

                <!-- 最小点赞数筛选 -->
                <div class="filter-item">
                  <label class="filter-label">最小点赞数</label>
                  <el-input
                      v-model.number="queryParams.minLiked"
                      placeholder="最小点赞数"
                      size="small"
                      type="number"
                      min="0"
                      class="min-liked-input"
                  ></el-input>
                </div>

                <!-- 作者筛选 -->
                <div class="filter-item">
                  <label class="filter-label">作者ID</label>
                  <el-input
                      v-model="queryParams.userId"
                      placeholder="作者ID"
                      size="small"
                      type="number"
                      class="user-id-input"
                  ></el-input>
                </div>

                <div class="filter-actions">
                  <el-button size="small" type="primary" @click="handleSearch" class="apply-btn">
                    <el-icon><Check /></el-icon>
                    应用筛选
                  </el-button>
                  <el-button size="small" @click="resetFilters" class="reset-btn">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>

      <!-- 作品网格区域 -->
      <div class="works-section">
        <div class="section-header">
          <h3>精选作品</h3>
          <p>发现社区中的精彩创作</p>
        </div>

        <div class="works-grid">
          <div
              v-for="work in filteredWorks"
              :key="work.sId"
              class="work-card-wrapper"
              @click="handleWorkClick(work.sId)"
          >
            <div class="work-card">
              <div class="work-cover">
                <img
                    :src="getCoverUrl(work.sCoverImg)"
                    :alt="work.sTitle"
                    class="cover-image"
                    loading="lazy"
                >
                <div class="work-overlay">
                  <div class="overlay-content">
                    <el-button type="primary" size="small" class="view-btn">
                      <el-icon><View /></el-icon>
                      查看详情
                    </el-button>
                  </div>
                </div>
                <div class="work-category-tag">{{ work.cgyName }}</div>
              </div>
              <div class="work-info">
                <div class="title-wrapper">
                  <h3 class="work-title">{{ work.sTitle }}</h3>
                </div>
                <p class="work-description" v-if="work.sDescription">{{ work.sDescription }}</p>
                <div class="work-meta">
                  <div class="author-info">
                    <div class="author-avatar">
                      <el-avatar :size="24" :src="getAvatarUrl(work.uAvatar)" />
                    </div>
                    <span class="author-name">{{ work.uNickName }}</span>
                  </div>
                  <span class="date">{{ formatDate(work.sCreateTime) }}</span>
                </div>
                <div class="work-stats">
                  <span class="stat-item">
                    <el-icon size="14"><View /></el-icon>
                    {{ work.sClick }}
                  </span>
                  <span class="stat-item">
                    <el-icon size="14"><Pointer /></el-icon>
                    {{ work.sLiked || 0 }}
                  </span>
                  <span class="stat-item">
                    <el-icon size="14"><Star /></el-icon>
                    {{ work.sCollect || 0 }}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态显示 -->
          <div v-if="filteredWorks.length === 0 && !loading" class="empty-state">
            <div class="empty-content">
              <el-empty description="暂无作品数据" :image-size="200">
                <el-button type="primary" @click="resetFilters">重置筛选条件</el-button>
              </el-empty>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="loading" class="loading-state">
            <div class="loading-content">
              <el-loading-spinner size="60"></el-loading-spinner>
              <p>正在加载作品...</p>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="filteredWorks.length > 0">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[8, 16, 24]"
              :total="totalWorks"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  ElCard,
  ElSelect,
  ElOption,
  ElInput,
  ElPagination,
  ElEmpty,
  ElIcon,
  ElLoading,
  ElDatePicker,
  ElButton,
  ElCollapse,
  ElCollapseItem,
  ElAvatar
} from 'element-plus';
import axios from '../api/index.js';
import { View, Search, Star, Pointer, Check, Refresh } from "@element-plus/icons-vue";

export default {
  name: 'CreationSquare',
  components: {
    View,
    ElCard,
    ElSelect,
    ElOption,
    ElInput,
    ElPagination,
    ElEmpty,
    ElIcon,
    Search,
    Star,
    Pointer,
    Check,
    Refresh,
    Loading: ElLoading,
    ElDatePicker,
    ElButton,
    ElCollapse,
    ElCollapseItem,
    ElAvatar
  },
  setup() {
    const router = useRouter();
    const route = useRoute();

    // 状态管理
    const currentPage = ref(1);
    const pageSize = ref(8);
    const sortOption = ref('createTime_desc'); // 默认按创建时间降序
    const loading = ref(false);
    const works = ref([]);
    const totalWorks = ref(0);
    const activeUsers = ref(128); // 模拟活跃用户数
    const categories = ref([
      { cgy_id: 1, cgy_name: "故事" },
      { cgy_id: 2, cgy_name: "博文" },
      { cgy_id: 3, cgy_name: "诗歌" },
      { cgy_id: 4, cgy_name: "活动" },
      { cgy_id: 5, cgy_name: "文章" }
    ]); // 分类数据
    const activeAdvancedFilters = ref([]); // 控制高级筛选面板展开/收起
    const getAvatarUrl = (avatarName) => {
      if (!avatarName) {
        return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
      }

      const baseURL = axios.defaults.baseURL || '';
      const cleanBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
      return `${cleanBaseURL}/img/avatar/${avatarName}`;
    };
    // 查询参数，与后端CreationQueryDTO对应
    const queryParams = ref({
      cgyId: null,
      userId: null,
      keyword: '',
      minCreateTime: null,
      maxCreateTime: null,
      minLiked: null,
      sortBy: 'createTime',
      sortDirection: 'DESC'
    });

    // 日期范围选择器的双向绑定值
    const dateRange = ref([]);

    // 获取作品数据
    const fetchWorks = async () => {
      try {
        loading.value = true;
        // 构建请求参数
        const params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value,
          ...queryParams.value
        };

        const response = await axios.get('/creation/works', { params });

        works.value = response.records;
        totalWorks.value = response.total || 0;

        // 为作品添加模拟描述
        works.value.forEach(work => {
          if (!work.sDescription) {
            work.sDescription = '这是一段关于作品的简要描述，展示了作品的主要内容和特点...';
          }
        });
      } catch (error) {
        console.error('获取作品数据失败:', error);
      } finally {
        loading.value = false;
      }
    };

    // 组件初始化
    onMounted(() => {
      // 从URL参数中读取页码
      const savedPage = route.query.page;
      if (savedPage) {
        currentPage.value = Number(savedPage);
      }
      fetchWorks();
    });

    // 监听页码变化，同步到路由参数
    watch(currentPage, (newPage) => {
      router.replace({
        name: 'CreationSquare',
        query: {
          ...route.query,
          page: newPage
        }
      });
    });

    // 处理排序变化
    const handleSortChange = (value) => {
      if (!value) return;
      const [sortBy, sortDirection] = value.split('_');
      queryParams.value.sortBy = sortBy;
      queryParams.value.sortDirection = sortDirection.toUpperCase();
      currentPage.value = 1; // 排序变化重置到第一页
      fetchWorks();
    };

    // 处理日期范围变化
    const handleDateRangeChange = (value) => {
      if (value && value.length === 2) {
        queryParams.value.minCreateTime = value[0];
        queryParams.value.maxCreateTime = value[1];
      } else {
        queryParams.value.minCreateTime = null;
        queryParams.value.maxCreateTime = null;
      }
    };

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1; // 搜索时重置到第一页
      fetchWorks();
    };

    // 重置筛选条件
    const resetFilters = () => {
      queryParams.value = {
        cgyId: null,
        userId: null,
        keyword: '',
        minCreateTime: null,
        maxCreateTime: null,
        minLiked: null,
        sortBy: 'createTime',
        sortDirection: 'DESC'
      };
      dateRange.value = [];
      sortOption.value = 'createTime_desc';
      currentPage.value = 1;
      fetchWorks();
    };

    // 处理作品点击事件
    const handleWorkClick = (workId) => {
      router.push({
        name: 'CreationDetailUser',
        params: { sId: workId }
      });
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString();
    };

    // 获取封面图片URL
    const getCoverUrl = (coverImg) => {
      if (!coverImg) {
        return 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=600&q=80';
      }
      const baseURL = axios.defaults.baseURL || '';
      const cleanBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
      return `${cleanBaseURL}/img/${coverImg}`;
    };

    // 筛选作品（保留前端筛选作为备份）
    const filteredWorks = computed(() => {
      let result = [...works.value];

      if (queryParams.value.keyword) {
        const keyword = queryParams.value.keyword.toLowerCase();
        result = result.filter(work =>
            work.sTitle.toLowerCase().includes(keyword) ||
            work.uNickName.toLowerCase().includes(keyword) ||
            (work.sKeyword && work.sKeyword.toLowerCase().includes(keyword))
        );
      }

      return result;
    });

    // 处理分页大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val;
      fetchWorks();
    };

    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fetchWorks();
    };

    return {
      currentPage,
      pageSize,
      sortOption,
      works,
      filteredWorks,
      totalWorks,
      loading,
      categories,
      queryParams,
      dateRange,
      activeAdvancedFilters,
      activeUsers,
      getAvatarUrl,
      handleWorkClick,
      formatDate,
      getCoverUrl,
      handleSizeChange,
      handleCurrentChange,
      handleSortChange,
      handleSearch,
      resetFilters,
      handleDateRangeChange
    };
  }
};
</script>

<style scoped>
.creation-square {
  background-color: #f8f9fa;
  min-height: 100vh;
}

/* 横幅区域 */
.banner-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 20px;
  text-align: center;
}

.banner-content {
  max-width: 1200px;
  margin: 0 auto;
}

.banner-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 16px;
}

.banner-subtitle {
  font-size: 1.2rem;
  opacity: 0.9;
  margin-bottom: 30px;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

.banner-stats {
  display: flex;
  justify-content: center;
  gap: 40px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 2rem;
  font-weight: 700;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.8;
  margin-top: 5px;
}

/* 容器 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

/* 区域标题 */
.section-header {
  margin-bottom: 24px;
}

.section-header h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.section-header p {
  color: #666;
  font-size: 0.95rem;
}

/* 筛选栏 */
.filter-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.filter-bar {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-label {
  font-size: 0.9rem;
  color: #555;
  font-weight: 500;
}

.filter-select {
  min-width: 150px;
}

.search-input {
  width: 250px;
}

/* 高级筛选 */
.advanced-filter {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.advanced-group {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  align-items: flex-end;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-actions {
  display: flex;
  gap: 10px;
  margin-top: 8px;
}

.apply-btn, .reset-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.min-liked-input, .user-id-input {
  width: 120px;
}

/* 作品区域 */
.works-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 30px;
}

.work-card-wrapper {
  transition: transform 0.3s ease;
  cursor: pointer;
}

.work-card-wrapper:hover {
  transform: translateY(-5px);
}

.work-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.work-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.work-cover {
  position: relative;
  width: 100%;
  height: 180px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.work-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.work-card:hover .work-overlay {
  opacity: 1;
}

.work-card:hover .cover-image {
  transform: scale(1.05);
}

.overlay-content {
  text-align: center;
}

.view-btn {
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  border: none;
}

.work-category-tag {
  position: absolute;
  top: 12px;
  left: 12px;
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 500;
}

.work-info {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.title-wrapper {
  margin-bottom: 8px;
}

.work-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.work-description {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.work-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 0.85rem;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-avatar {
  display: flex;
}

.author-name {
  color: #555;
  font-weight: 500;
}

.date {
  color: #888;
  font-size: 0.8rem;
}

.work-stats {
  display: flex;
  gap: 15px;
  margin-top: auto;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #888;
  font-size: 0.85rem;
}

/* 空状态和加载状态 */
.empty-state, .loading-state {
  grid-column: 1 / -1;
  padding: 60px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-content, .loading-content {
  text-align: center;
}

.loading-content p {
  margin-top: 16px;
  color: #666;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .banner-section {
    padding: 40px 20px;
  }

  .banner-title {
    font-size: 2rem;
  }

  .banner-stats {
    gap: 20px;
  }

  .filter-bar {
    flex-direction: column;
    gap: 15px;
  }

  .filter-group {
    width: 100%;
  }

  .search-input {
    width: 100%;
  }

  .advanced-group {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-item {
    width: 100%;
  }

  .min-liked-input, .user-id-input {
    width: 100%;
  }

  .works-grid {
    grid-template-columns: 1fr;
  }

  .container {
    padding: 20px 15px;
  }

  .filter-section, .works-section {
    padding: 20px;
  }
}

@media (min-width: 1200px) {
  .works-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}
</style>